<?php

namespace App\Jobs;

use App\Models\SendGroupSms;
use App\Models\SendGroupSmsLog;
use App\Models\SendSmsType;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;

/**
 * 发送用户通知信息
 * Class SendGroupNotification
 * @package App\Jobs
 */
class SendGroupNotification extends Job
{
    /**
     * @var string 群发组id
     */
    protected $groupSmsId;

    /**
     * @var array 被发送电话
     */
    protected $phones;

    /**
     * @var array 短信配置
     */
    protected $gateways;

    /**
     * @var string 发送内容
     */
    protected $content;

    /**
     * Create a new job instance.
     * SendGroupNotification constructor.
     * @param int $groupSmsId
     * @param array $phones
     * @param $gateways
     * @param string $content
     */
    public function __construct(int $groupSmsId, array $phones, $gateways, string $content)
    {
        $this->groupSmsId = $groupSmsId;

        //如果没有选择用户，则默认本站所有用户
        $this->phones = $phones ?: User::whereNotNull('phone')->get('phone')->toArray();
        $this->gateways = $gateways;
        $this->content = $content;
    }

    /**
     * Execute the job.
     *
     * @return mixed
     */
    public function handle()
    {
        try {

            //可能是多个号码，分割成多个小队列
            foreach ($this->phones as $phone){

                //存入发送记录
                $logId = SendGroupSmsLog::insertGetId(
                        ['group_sms_id'=>$this->groupSmsId,
                        'phone'=>$phone,
                        'status'=>SENDING_SMS,
                        'created_at'=>Carbon::now(),
                        'updated_at'=>Carbon::now()]);

                //正式发送
                dispatch((new SendUserSms($phone, $this->content, $logId, $this->gateways))
                    ->onQueue('high'));
            }

        } catch (\Exception $e) {
            Log::error('分发短信失败 ', (array)$e->getMessage());
            return false;
        }
    }
}
